package logic

import (
	"context"
	"io"
	"net/http"

	"goNutpi/internal/svc"
	"goNutpi/internal/types"

	"github.com/tidwall/gjson"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpc"
)

type GetTagsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetTagsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetTagsLogic {
	return &GetTagsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetTagsLogic) GetTags() (resp *types.TagResp, err error) {
	// todo: add your logic here and delete this line
	url := "https://api.nutpi.net/allTag"
	res, err_ := httpc.Do(l.ctx, http.MethodGet, url, nil)
	if err_ != nil {
		l.Error(err_)
		return nil, err_
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		l.Errorf("Failed to read response body:", err)
		return nil, err
	}
	//格式化输出json
	//var str bytes.Buffer
	//_ = json.Indent(&str, []byte(body), "", "    ")
	//l.Debugf("formated: ", str.String())
	//l.Debug(keyValue)
	var responseData []types.TagItem
	var item types.TagItem
	recs := gjson.ParseBytes(body)
	recs.ForEach(func(key, value gjson.Result) bool {
		item.Id = value.Get("id").String()
		item.Name = value.Get("name").String()
		item.Sort = value.Get("sort").Int()
		item.Image = value.Get("image").String()
		responseData = append(responseData, item)
		return true // keep iterating
	})

	//t := reflect.TypeOf(keyVal["count"])
	//l.Debugf("Type: %v\n", t)

	if len(responseData) != 0 {
		resp = &types.TagResp{
			Code:    0,
			Message: res.Status,
			Data:    responseData,
		}
	} else {
		resp = &types.TagResp{
			Code:    400,
			Message: res.Status,
			Data:    responseData,
		}
	}
	return resp, nil
}
